<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
          v-allow="'import_excel'"
            @click="$router.push('/import')"
            type="warning"
            size="small"
            >excel导入</el-button
          >
          <el-button v-allow="'export_excel'" @click="exportExcel" type="danger" size="small"
            >excel导出</el-button
          >
          <el-button v-allow="'add'" @click="showDialog = true" type="primary" size="small"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- 显示员工的头像 -->
          <el-table-column label="员工头像" width="100px">
            <template #default="{ row }">
              <img
                @click="showCode(row.staffPhoto)"
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 使用作用域插槽自定义内容展示数据 -->
            <template #default="{ row }">
              {{ formData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <!-- 查询参数传值 this.$route.query -->
              <el-button
                @click="$router.push(`/employess/detail?userId=${row.id}`)"
                type="text"
                size="small"
                >查看</el-button
              >
              <!-- 路径参数传递页面 -->
              <!-- <el-button @click="$router.push(`/employess/detail/${row.id}`)" type="text" size="small">查看</el-button> -->
              <el-button @click="hAssignRole(row.id)" type="text" size="small"
                >分配角色</el-button
              >
              <el-button v-allow="'delete'" @click="hDel(row.id)" type="text" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </el-card>
      <!-- 实现新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addEmployees
          v-if="showDialog"
          @success="hSuccess"
          @close="showDialog = false"
        />
      </el-dialog>
      <!-- 生成二维码的图片 -->
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="AssignRoleDialog">
        <AssignRole @close="AssignRoleDialog=false" v-if="AssignRoleDialog" :curId="curId" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addEmployees from "./employDialog.vue";
import { delEmployee, getEmployees } from "@/api/employees";
import employeesEnum from "@/constant/employees";
import QrCode from "qrcode";
import AssignRole from "./assignRole.vue";
export default {
  components: {
    addEmployees,
    AssignRole,
  },
  data() {
    return {
      curId: "",
      AssignRoleDialog: false,
      list: [],
      page: 1,
      size: 10,
      total: 0,
      showDialog: false,
      showCodeDialog: false,
    };
  },
  created() {
    this.loadEmployees();
    // console.log(employeesEnum);
  },
  methods: {
    hAssignRole(id) {
      this.AssignRoleDialog = true;
      this.curId = id;
    },
    showCode(url) {
      this.showCodeDialog = true;
      this.$nextTick(() => {
        const canvas = this.$refs.myCanvas;
        QrCode.toCanvas(canvas, url); // 将地址转化成二维码
      });
    },
    exportExcel() {
      const { tHeader, data } = this.transZhKeyToExcel(this.list);
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import("@/vendor/Export2Excel").then((excel) => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType,
        });
      });
    },
    transZhKeyToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };

      //1.生成表头
      const one = list[0];
      if (!one) return;
      const tHeader = Object.keys(one).map((enkey) => {
        return mapInfo[enkey];
      });
      // console.log(tHeader,'tHeader');

      const data = list.map((item) => {
        return Object.values(item);
      });
      // console.log(data,'data');
      return { tHeader, data };
    },
    //删除功能
    hDel(id) {
      this.$confirm("您确定要删除该员工吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //确定之后实现删除
          const res = await delEmployee(id);
          console.log(res);
          if (res.code === 10000) {
            this.$message.success(res.message);
            //判断当前页面是否只剩下1条数据
            if (this.list.length === 1) {
              this.page--;
              if (this.page <= 0) {
                this.page = 1;
              }
            }
            this.loadEmployees();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //关闭弹层，重新渲染
    hSuccess() {
      this.total++;
      //计算出最大的页码值
      const maxPage = Math.ceil(this.total / this.size);
      //将页码值切换为最后一页
      this.page = maxPage;
      this.loadEmployees();
      this.showDialog = false;
    },
    handleCurrentChange(val) {
      //当前页码值切换时触发
      this.page = val;
      this.loadEmployees();
    },
    //格式化数据的函数
    formData(id) {
      // console.log(id,'id');
      //将1 或 2 转换为 正式或非正式
      const hireType = {};
      employeesEnum.hireType.forEach(
        (item) => (hireType[item.id] = item.value)
      );

      // return hireType[id]||'未知'
      //  hireType = employeesEnum.hireType.reducee((acc, item) => {
      //   acc[item.id] = item.value;
      //   return acc;
      // }, {});
      return hireType[id] || "未知";
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size });
        // console.log(res);
        if (res.code !== 10000) return this.$message.error(res.message);
        this.$message.success(res.message);
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>
